package samsung.sds.groupManagement.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import samsung.sds.groupManagement.model.GroupEntity;
import samsung.sds.groupManagement.model.GroupUserEntity;
import samsung.sds.groupManagement.service.GroupManagementService;
import samsung.sds.groupManagement.service.GroupUserManagementService;
import samsung.sds.system.common.baseQuery.model.PageData;
import samsung.sds.system.common.model.QueryParam;
import samsung.sds.system.utils.CommonTools;
import samsung.sds.system.utils.Constants;
import samsung.sds.userManagement.model.UserEntity;

/**
 * @author wch.wu & lulu.yuan&zhukui.shi
 * @createDate 2016-01-07
 * 
 * 用户组管理Controller
 */
@Controller
@RequestMapping("/groupManagement")
public class GroupManagementController{

	@Autowired
	private GroupManagementService groupManagementServiceImpl;
	
	@Autowired
	private GroupUserManagementService groupUserManagementServiceImpl;
	
	/**
	 * 进入用户组列表展示页面
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/userGroupList" , method=RequestMethod.POST)
	public String userGroupList(HttpServletRequest request, Map<String, Object> map) {
		String createUser = request.getParameter("createUser");
		List<GroupEntity> groupList = groupManagementServiceImpl.selectUserGroupList(createUser,map);
		map.put("groupList", groupList);
		return "/groupManagement/groupList";

	}
	
	/**
	 * 根据组名（或创建组用户名）查询所有相关组信息[查询这个用户创建的所有组]
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/selectUserGroupList",method=RequestMethod.POST)
	@ResponseBody
	public List<GroupEntity> selectUserGroupList(HttpServletRequest request , Map<String, Object> map) {
		
		// 获取当前系统用户
		String createUser = request.getParameter("createUser");
		List<GroupEntity> groupList = groupManagementServiceImpl.selectUserGroupList(createUser,map );
		return groupList;
	}
	
	/**
	 * 用户创建组
	 * @param groupEntity
	 * @throws ParseException 
	 * @throws IOException 
	 */
	@RequestMapping(value="/insertGroup",method=RequestMethod.POST)
	@ResponseBody
	public int insertGroup(GroupEntity groupEntity) throws ParseException, IOException{
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
		// 新建组，组号在原来的最大值的基础上加1
		groupEntity.setGroupId( CommonTools.getKeyUUID() );
		Date createDate = new Date();
		groupEntity.setCreateTime( format.parse(format.format(createDate)) );
		groupEntity.setLastModifyTime( format.parse(format.format(createDate)) );
		int count = groupManagementServiceImpl.insertEntity(groupEntity);
		return count;
	}
	
	/**
	 * 用户更新组
	 * @param groupEntity
	 * @throws ParseException 
	 */
	@RequestMapping(value="/updateGroup",method=RequestMethod.POST)
	@ResponseBody
	public int updateGroup(GroupEntity groupEntity) throws ParseException{
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
		Date createDate = new Date();
		groupEntity.setLastModifyTime( format.parse(format.format(createDate)) );
		int count = groupManagementServiceImpl.updateEntity(groupEntity);
		return count;
	}

	/**
	 * 删除选中的组并且删除组相关联的用户和问卷关联关系
	 * （删除多个组的时候，传入参数是groupId集合字符串，如：“1,2,4”）
	 * 
	 * @param request
	 * @throws ParseException 
	 */
	@RequestMapping(value="/deleteGroups",method=RequestMethod.POST)
	@ResponseBody
	public int deleteGroups(HttpServletRequest request) throws ParseException{
		
		List<String> groupIds = new ArrayList<String>();
		String groupIdStr = request.getParameter("groupIds");
		String[] groupIdArr =  groupIdStr.split(",");
		int count;
		for (String temGroupId : groupIdArr) {
			String groupId = new String( temGroupId );
			groupIds.add( groupId );
			int userCount = groupManagementServiceImpl.selectGroupUsersCount(groupId);
			if( userCount > 0){
				count = -1;
				return count;
			}
		}
		count = groupManagementServiceImpl.deleteUserGroupsByGroupIds(groupIds);
		return count;
	}
	
	/**
	 * 给组中添加用户
	 * @param request
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/insertUsersToGroup",method=RequestMethod.POST)
	@ResponseBody
	public String insertUsersToGroup(HttpServletRequest request) throws UnsupportedEncodingException {
		
		String temGroupId = request.getParameter("groupId");
		String groupId;
		if( null != temGroupId && !"".equals(temGroupId) ){
			 groupId = new String(temGroupId);
		}else{
			return Constants.FAILURE_CODE;
		}
		
		String userNamesStr = request.getParameter("userNames");
		String temUserName;
		if( null != userNamesStr ){
			//对字符串进行URL解码处理
			temUserName = URLDecoder.decode(userNamesStr, "UTF-8");
		}else{
			return Constants.FAILURE_CODE;
		}
		
		if( null != temUserName ){ 
			//需要增加的用户名称
			String[] userNamesArr = temUserName.split(",");  
			//将他们放进一个ArrayList
			List<String> addnew = new ArrayList<String>();
			for(int i=0;i<userNamesArr.length;i++){
			String userName = userNamesArr[i];
			addnew.add(userName); 
			}  
			 
			//取得已有的用户名称
			List<GroupUserEntity> existNamesArr = groupUserManagementServiceImpl.queryExistGroupUsersListPage(groupId); 
			//将他们放进一个ArrayList
			List<String> alreadyexist = new ArrayList<String>();
			  for(int j=0;j<existNamesArr.size();j++){ 
				String existName = existNamesArr.get(j).getUserName();
				alreadyexist.add(existName); 
			 } 
			  //两个数组对比去重
			  addnew.removeAll(alreadyexist); 
			  String[] userNamesArr1 = (String[])addnew.toArray(new String[addnew.size()]); 
			  
			this.groupUserManagementServiceImpl.InsertUsesToGroup(userNamesArr1, groupId);
			return Constants.SUCCESS_CODE;
		}else{
			return Constants.FAILURE_CODE;
		} 
	}

	/**
	 * 从组中删除用户
	 * @param request
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/deleteUsersFromGroup",method=RequestMethod.POST)
	@ResponseBody
	public String deleteUsersFromGroup(HttpServletRequest request) throws UnsupportedEncodingException{
		
		String userNamesStr = request.getParameter("username");
		String groupId = new String(request.getParameter("groupId"));
		//对字符串进行URL解码处理
		String temUserName = URLDecoder.decode(userNamesStr, "UTF-8");
		
		List<String> userNames = new ArrayList<String>();
		if( null != temUserName ){
			String[] userNameArr = temUserName.split(",");
			for (String userName : userNameArr){
					userNames.add( userName );
			}
		}
		//删除用户
		int count = groupUserManagementServiceImpl.deleteUsersFromGroup( userNames, groupId );
		if(count > 0){
			return Constants.SUCCESS_CODE;
		}else{
			return Constants.FAILURE_CODE;
		}
	}
	
	/**
	 * 查找已经加入到这个组下面的所有用户（调用用户表分页接口）
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/queryUsersInGroup",method=RequestMethod.POST)
	@ResponseBody
	public PageData<UserEntity> queryUsersInGroup(HttpServletRequest request){
		
		QueryParam param = CommonTools.getQueryParam(request);
		return groupUserManagementServiceImpl.queryUsersListPage(param );
	}
	
	/**
	 * 查找所有用户（调用用户表分页接口）
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/queryUsersNotInGroup",method=RequestMethod.POST)
	@ResponseBody
	public PageData<GroupUserEntity> queryUsersNotInGroup(HttpServletRequest request){
		
		QueryParam param = CommonTools.getQueryParam(request);
		return groupUserManagementServiceImpl.queryNoGroupUsersListPage(param );
	}  
	
	/**
	 * 弹出用户查询窗口，跳转至添加用户窗口
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/addUserForGroup_sitemesh_popup",method=RequestMethod.GET)
	public String groupUserSelectPopup(ModelMap model){		
		return "/groupManagement/addUserPopup";
	}
	
	/**
	 * 校验组名是否已经存在（不允许同一用户创建重名的组）
	 * @param request
	 * @param groupEntity
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/groupNameValidate",method=RequestMethod.POST)
	@ResponseBody
	public boolean groupNameValidate(HttpServletRequest request,GroupEntity groupEntity) throws IOException{
		
		// 返回验证结果标记
		boolean validateResult = true;
		String groupId = null;
		Integer operateType = Integer.parseInt(request.getParameter("operateType"));
		if( operateType == Constants.OPERATE_UPDATE ){
			groupId = groupEntity.getGroupId();
		} else {
			groupEntity.setGroupId(groupId);
		}
		// 查询是否已经存在相同数据
		GroupEntity temGroupEntity = groupManagementServiceImpl.findUniqueByProperty( groupEntity );
		if( null != temGroupEntity ){
			// 该用户下的组已经存在
			validateResult = false;
		}
		return validateResult;
	}
	
}
